package com.tianbao54.concurrent.semaphore;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {

    public static void main(String[] args) {

        ExecutorService service = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0 ; i < 10 ; i ++) {
            service.submit(new Job(semaphore,"name" + i));
        }
        service.shutdown();
    }

    static class Job implements Runnable {

        private final Semaphore semaphore;
        private final String name;

        Job (Semaphore semaphore,String name) {
            this.semaphore = semaphore;
            this.name = name;
        }

        @Override
        public void run() {

            try {
                semaphore.acquire();
                System.out.println(name + " 已经进入，当前有 " + (3 - semaphore.availablePermits()) + " 个线程并发");

                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                System.out.println(name + " 即将离开");
                semaphore.release();
                System.out.println(name + " 已经离开，当前有 " + (3 - semaphore.availablePermits()) + " 个线程并发");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
